package com.hzhk.happyrent.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hzhk.happyrent.R;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.view.SwitchButton;
import com.hzhk.happyrent.utils.MyPerference;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.tamic.novate.Throwable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateAddressActivity extends Activity {

    @BindView(R.id.update_address_name)
    EditText updateAddressName;
    @BindView(R.id.update_address_phoneNo)
    EditText updateAddressPhoneNo;
    @BindView(R.id.update_address_select)
    RelativeLayout updateAddressSelect;
    @BindView(R.id.update_address_detail)
    EditText updateAddressDetail;
    @BindView(R.id.address_update)
    Button addressUpdate;
    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.activity_titlebar_right)
    TextView activityTitlebarRight;
    @BindView(R.id.update_address_show_select)
    TextView updateAddressShowSelect;
    @BindView(R.id.switch1)
    SwitchButton switch1;
    private Logger log = LoggerFactory.getLogger(this.getClass().getName());
    private String type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_address);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        if (type != null) {
            activityTitlebarCenter.setText(R.string.edit_address);
            updateAddressName.setText(intent.getStringExtra("name"));
            updateAddressPhoneNo.setText(intent.getStringExtra("phone"));
            updateAddressDetail.setText(intent.getStringExtra("address"));
            updateAddressShowSelect.setText(intent.getStringExtra("area"));
            switch1.setChecked(intent.getStringExtra("check_default").equals("1") ? true:false);
        } else {
            activityTitlebarRight.setVisibility(View.GONE);
            activityTitlebarCenter.setText(R.string.update_address);
        }
    }

    @OnClick({R.id.update_address_name, R.id.update_address_phoneNo, R.id.update_address_select, R.id.update_address_detail, R.id.address_update, R.id.activity_titlebar_left, R.id.activity_titlebar_center, R.id.activity_titlebar_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.update_address_name:
                break;
            case R.id.update_address_phoneNo:
                break;
            case R.id.update_address_select:
                //判断输入法的隐藏状态
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    selectAddress();//调用CityPicker选取区域
                }
                break;
            case R.id.update_address_detail:
                break;
            case R.id.address_update:
                judgeMessageInput();
                break;
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.activity_titlebar_center:
                break;
            case R.id.activity_titlebar_right:
                initDelData();
                break;
        }
    }

    private void initDelData() {

        Map<String, Object> map = new HashMap<>();
        if (type != null)
            map.put("user_address_id", type);
        map.put("user_id", MyPerference.getInstance().getUserId());

        HttpManager.getInstance().perform_post(API.DEL_ADDRESS, map, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                log.debug("response = " + tag);
//                Toast.makeText(AddressActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                log.debug("response = " + response);
                //CardHotModel  cardHotModel = new Gson().fromJson(response,CardHotModel.class);
                //addressAdapter.setList(cardHotModel.getData().getCards());
                finish();
            }
        });
    }


    private void selectAddress() {
        CityPicker cityPicker = new CityPicker.Builder(UpdateAddressActivity.this)
                .textSize(14)
                .title("地址选择")
                .titleBackgroundColor("#FFFFFF")
                //.titleTextColor("#696969")
                .confirTextColor("#696969")
                .cancelTextColor("#696969")
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                //.textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];
                //为TextView赋值
                updateAddressShowSelect.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
            }
        });

    }

    private void judgeMessageInput() {
        if (TextUtils.isEmpty(updateAddressName.getText().toString())) {
            Toast.makeText(this, "请输入收货人姓名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(updateAddressPhoneNo.getText().toString())) {
            Toast.makeText(this, "请输入收货人手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(updateAddressName.getText().toString())) {
            Toast.makeText(this, "请输入收货人地址", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(updateAddressName.getText().toString())) {
            Toast.makeText(this, "请输入收货人详细地址", Toast.LENGTH_SHORT).show();
            return;
        }
        initData();

    }

    private void initData() {

        String name = updateAddressName.getText().toString();
        String phone = updateAddressPhoneNo.getText().toString();
        String detail = updateAddressDetail.getText().toString();
        String area = updateAddressShowSelect.getText().toString();
        log.debug("user_address_id = " + type);
        log.debug("user_id = " + MyPerference.getInstance().getUserId());
        log.debug("name = " + name);
        log.debug("phone = " + phone);
        log.debug("detail = " + detail);
        log.debug("area = " + area);
        log.debug("check_default = " + (switch1.isChecked()? "1":"0"));

        Map<String, Object> map = new HashMap<>();
        if (type != null)
        map.put("user_address_id", type);
        map.put("user_id", MyPerference.getInstance().getUserId());
        map.put("user_name", name);
        map.put("phone", phone);
        map.put("address", detail);
        map.put("area", area);
        map.put("check_default", switch1.isChecked()? "1":"0");
        HttpManager.getInstance().perform_post(API.EDIT_ADDRESS, map, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                log.debug("response = " + tag);
//                Toast.makeText(AddressActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                log.debug("response = " + response);
                //CardHotModel  cardHotModel = new Gson().fromJson(response,CardHotModel.class);
                //addressAdapter.setList(cardHotModel.getData().getCards());
                finish();
            }
        });
    }



}
